/*****************************************************************************
 *   Copyright 2005 Tim A Wang
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 ****************************************************************************/
package com.jb.web.session;

import com.jb.framework.Container;
import com.jb.framework.PersistentContext;
import com.jb.framework.PersistentManager;
import com.jb.web.application.configuration.Config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

//
//session container
//
public class SessionManager extends Container {
    static SessionManager sessionManager;

    private SessionManager() {
        super();
    }
    /**
     * Find or locate client Session.
     * @param request the request
     * @return a Session object
     */
    public static Session findOrCreate(HttpServletRequest request) {
        Session session = find(request);
        if (session == null) {
            HttpSession httpSession = request.getSession(true);
            String sessionId = httpSession.getId();
            session = (Session) getSessionManager().create(new SessionManager.SessionContext(), sessionId, Session.class);
            if(session==null)
                return null;
            httpSession.setAttribute(Config.getInstance().getDefaultPage() + sessionId, session);
        }else {
            session.validate();
        }
        return session;
    }

    static SessionManager getSessionManager() {
        if (sessionManager == null) {
            sessionManager = new SessionManager();
        }
        return sessionManager;
    }
    
    static private Session find(HttpServletRequest request) {
        HttpSession httpSession = request.getSession(true);
        String sessionId = httpSession.getId();
        Session session = (Session) httpSession.getAttribute(Config.getInstance().getDefaultPage() + sessionId);
        return session;
    }

    public static class SessionContext implements PersistentContext {
        public String getApplicationName() {
            return "JBSessionMgr";
        }

        public PersistentManager getPersistentManager() {
            return null;
        }
    }
}
